#pragma once
#include<iostream>
#include<pthread.h>
#include<string>
#include<queue>

using namespace std;

#define maxdefault 10

template<class T>
class blockqueue
{
public:
    blockqueue(int maxcap = maxdefault)
    :_maxcap(maxcap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
    }

    T pop()
    {
        pthread_mutex_lock(&_mutex);
        if(_q.size() == 0) pthread_cond_wait(&_c_cond,&_mutex);
        T data = _q.front();
        _q.pop();

        pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_mutex);
        return data;
    }


    void push(const T& in)
    {
        pthread_mutex_lock(&_mutex);
        if(_maxcap == _q.size()) pthread_cond_wait(&_p_cond,&_mutex);
        //放进阻塞队列
        _q.push(in);
        
        pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_mutex);

    }
    ~blockqueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

private:
    queue<T> _q;
    int _maxcap;

    pthread_mutex_t _mutex;
    pthread_cond_t _c_cond;
    pthread_cond_t _p_cond;
};